package _02_链表;

/**
 * https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
 * @Author: haogege
 * @Date: 2021/9/20
 */
public class _19_删除链表的倒数第N个结点 {


    // 使用2个指针，它们两相隔n
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // n = 2
        ListNode first = head;
        ListNode second = first;
        for (int i = 0; i < n; i++) {
            second = second.next;
        }
        if (second == null) {
            return head.next;
        }
        while (second.next != null) {
            first = first.next;
            second = second.next;
        }
        first.next = first.next.next;
        return head;
    }

}
